#!/usr/bin/python3
# -*- coding: utf-8 -*-

from ._commons import db


class NodePO(db.Model):
    """节点。"""
    __tablename__ = 'NODE'

    name = db.Column('NODE_NAME', db.String(100), primary_key=True, nullable=False)
    description = db.Column('DESCRIPTION', db.String(500))
    hostname = db.Column('HOST_NAME', db.String(100))
    bundle = db.Column('BUNDLE', db.String(40))
    enabled = db.Column('ENABLED', db.Boolean, default=True, nullable=False)
    props = db.relationship('NodePropPO', lazy='select', cascade='all,delete-orphan')

    def set_props(
            self,
            value: dict = None,
            **props
    ):
        """ 设置节点的属性字典。

        :param value: 属性字典。
        :param props: 所有的属性字典。
        """
        self.props.clear()
        if value:
            for key_, value_ in value.items():
                self._add_prop(key_, value_)
        if props:
            for key_, value_ in props.items():
                self._add_prop(key_, value_)

        return self

    def _add_prop(
            self,
            key: str,
            value: str
    ):
        if key is None or key.isspace():
            return

        self.props.append(NodePropPO(key=key.strip(), value=value))

    @property
    def prop_dict(self):
        return dict((p.key, p.value) for p in self.props)


class NodePropPO(db.Model):
    """节点关联的属性。"""
    __tablename__ = 'NODE_PROP'

    node_name = db.Column('NODE_NAME', db.ForeignKey('NODE.NODE_NAME'), primary_key=True, nullable=False)
    key = db.Column('P_KEY', db.String(100), primary_key=True, nullable=False)
    value = db.Column('P_VALUE', db.String(100), nullable=False)
